import {messages,queryCurrencyPrecision} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Button, InputNumber, message, Checkbox, Modal, Divider, Switch, DatePicker, Row, Col, Icon} from 'antd';
import moment from 'moment';
import 'styles/setting/currency-setting/currency-setting-edit.scss';
import menuRoute from "routes/menuRoute";
let dateChanged = 0;
let rateChanged = 0;
import ResizeTable from "components/resize-table";
import CurrencySettingService from "containers/setting/currency-setting/currency-setting.service";

class CurrencySettingEdit  extends React.Component{
  constructor (props){
    super(props);
    this.state = {
      isBaseCurrency: '',//是否是本位币汇率
      data: [],
      page: 0,
      pagination: { total: 0},
      visible: false,
      originalRate: 0,
      originalRecord: {},
      record: {},
      currencyRateOid: "",
      operatedRecord: {},//当前操作的表格里的某一条数据
      outEditRate: false,//点击表格外的更改汇率
      historyRateSave: false,//模态框里的更改历史汇率的确认
      outEditRateSave: false,
      startDate: null,//查询历史汇率的起始日期
      endDate: null,//查询历史汇率的截止日期
      language: this.props.language.code,
      columns: [
        {title: messages('setting.key405'/*编号*/), dataIndex: 'index',width: 60,
          render: (text, record, index) => {return index+1}},
        {title: messages('setting.key401'/*汇率生效日期*/), dataIndex: 'applyDate',
          render: (text) => {return (moment(text).local().format('YYYY-MM-DD'))}},
        {title: messages('setting.key406'/*外币*/), dataIndex: 'currencyCode'},
        {title: messages("common.currency.rate")/*汇率*/, dataIndex: 'rate'},
        {title: messages('setting.key407'/*本币*/), dataIndex: 'baseCurrencyCode'},
        {title: messages('setting.key408'/*修改时间*/), dataIndex: 'lastModifiedDate',
          render: (text) => {return (moment(text).local().format('YYYY-MM-DD HH:mm:ss'))}},
        {title: this.props.tenantMode ? '操作' : '', dataIndex: 'operation', width: this.props.language.code === 'zh_cn' ? '7%' : '10%',
          render: (text, record) => this.displayOperation(text, record)},
      ],
      setOfBooksId: this.props.params.setOfBooksId,
      currencyCode: this.props.params.currencyCode,
      enableAutoUpdate: false,
      loading: false,
      saveLoading: false,
    };
    this.currencySetting = menuRoute.getRouteItem('currency-setting', 'key');
  };

  componentWillMount (){
    this.getCurrencyDetail();
    this.getAutoRate();
  };

  //获取当条数据的详情
  getCurrencyDetail = () => {
    const {language, currencyCode, setOfBooksId} = this.state;
    let param = {
      currencyCode,
      setOfBooksId,
      language,
    };
    CurrencySettingService.getCurrencyDetail(param)
      .then(res => {
        this.setState({
          record: res.data,
          originalRecord: JSON.parse(JSON.stringify(res.data))
        }, () => {
          this.dataTransform();
        })
      })
  };

  getAutoRate = () => {
    const {setOfBooksId} = this.state;
    let params = {setOfBooksId, tenantId: this.props.company.tenantId};
    CurrencySettingService.getAutoRate(params)
      .then(res => {
        this.setState({
          enableAutoUpdate: res.data.rows,
        });
      })
  };

  dataTransform = () => {
    let record = this.state.record;
    this.setState({
      isBaseCurrency: record.currencyName === record.baseCurrencyName,
    }, () => {
      if (!this.state.isBaseCurrency) {
        this.getRateHistory();
      }
    });
  };

//什么时候显示列表里的更改
  displayOperation = (text, rec) => {
    const {record} = this.state;
    if (!record.enableAutoUpdate && this.props.tenantMode) {
      return (
        <a onClick={(event) => this.onOperation(event, rec)}>
          {messages('setting.key409'/*更改*/)}
        </a>
      )
    }
  };

  //点击查询
  onSearch = () => {
    this.setState({
      page: 0,
    }, () => {
      this.getRateHistory();
    });
  };

  //获取表格数据
  getRateHistory = () => {
    const {page, language, currencyCode, setOfBooksId, startDate, endDate} = this.state;
    let item = {currencyCode, setOfBooksId, language, page, size: 10,};
    let searchParam = {
      endDate: endDate ? endDate.utc().format('YYYY-MM-DD 23:59:59') : null,
      startDate: startDate ? startDate.utc().format('YYYY-MM-DD 00:00:00') : null,
    };
    let params = Object.assign(searchParam, item);
    this.setState({
      loading: true,
    });
    CurrencySettingService.getRateHistory(params)
      .then(res => {
          this.setState({
            data: res.data.rows,
            loading: false,
            pagination: {
              total: res.data.total,
              onChange: this.onChangePager,
              current: this.state.page + 1
            },
          })
        })
      .catch(err => {
        this.setState({
          loading: false,
        });
      })
  };

  //分页点击
  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1,
      }, () => {
        this.getRateHistory();
      })
  };
  //编辑汇率的启用与否
  onEnableRate = (e) => {
    const {record} = this.state;
    let param = {
      currencyRateOid: record.currencyRateOid,
      enable: e,
    };
    if (e) {
      this.enableRate(param);
    } else {
      this.disableRate(param);
    }
  };

  enableRate = (param) => {
    Modal.confirm({
      title: messages('setting.key410'/*启用*/),
      content: messages('setting.key411'/*启用该币种会影响全公司员工报销*/),
      okText: messages('setting.key412'/*继续更新*/),
      cancelText: messages('setting.key413'/*取消更新*/),
      onOk: () => {
        CurrencySettingService.onEnableRate(param)
          .then(res => {
            message.success(messages("common.operate.success")/*操作成功*/);
            this.getCurrencyDetail();
          })
      },
      onCancel: () => {
      },
    });
  };

  disableRate = (param) => {
    Modal.confirm({
      title: messages("common.disabled")/*禁用？*/,
      content: messages('setting.key414'/*禁用该币种会影响全公司员工报销*/),
      okText: messages('setting.key412'/*继续更新*/),
      cancelText: messages('setting.key413'/*取消更新*/),
      onOk: () => {
        CurrencySettingService.onEnableRate(param)
          .then(res => {
              message.success(messages("common.operate.success")/*操作成功*/);
              this.getCurrencyDetail();
            }
          )
      },
      onCancel: () => {
      },
    });
  };

  //点击表格外的更改汇率
  onOutEditRate = () => {
    this.setState({
      outEditRate: true,
    })
  };

  //点击表格外的更改汇率,生效日期变化时
  outApplyDateChange = (date) => {
    dateChanged = 1;
    const {record} = this.state;
    record.applyDate = date;
    this.setState({
      record,
      outEditRateSave: true,
    })
  };

  //点击表格外的更改汇率,生效汇率变化时
  outRateChange = (value) => {
    rateChanged = 1;
    const {record} = this.state;
    record.rate = value;
    this.setState({
      record,
      outEditRateSave: true,
    });
  };

  //点击表格外的更改汇率的取消
  onOutEditRateCancel = () => {
    dateChanged = 0;
    rateChanged = 0;
    this.setState({
      outEditRate: false,
      record: JSON.parse(JSON.stringify(this.state.originalRecord))
    })
  };

  //点击表格外的更改汇率的保存
  onOutEditRateSave = () => {
    const {record, originalRecord} = this.state;
    if (typeof (record.rate) !== 'number' || record.rate <= 0) {
      message.error(messages('setting.key403'/*生效汇率必须为大于0的数字*/) /*生效汇率必须为大于0的数字*/)
    } else {
      if (!dateChanged) {
        record.applyDate = moment(new Date()).utc().format();
        this.setState({
          record,
        }, () => {
          if (moment(record.applyDate).format('YYYY-MM-DD') === moment(originalRecord.applyDate).format('YYYY-MM-DD') && record.rate === originalRecord.rate) {
            message.error(messages('setting.key415'/*不能保存重复数据*/) /*不能保存重复数据*/)
          } else {
            this.saveRecord(record);
          }
        })
      } else {
        if (moment(record.applyDate).format('YYYY-MM-DD') === moment(originalRecord.applyDate).format('YYYY-MM-DD') && record.rate === originalRecord.rate) {
          message.error(messages('setting.key415'/*不能保存重复数据*/) /*不能保存重复数据*/)
        } else {
          this.saveRecord(record);
        }
      }
    }
  };

  saveRecord = (record) => {
    this.setState({
      saveLoading: true,
    });
    CurrencySettingService.onOutEditRateSave(record)
      .then(res => {
        this.getCurrencyDetail();
        this.setState({
          outEditRate: false,
          saveLoading: false,
        }, () => {
          dateChanged = 0;
        })
      })
      .catch(err => {
        this.setState({
          saveLoading: false,
        });
      });
  };

  //是否启用自动汇率
  onEnableAutoUpdate = (e) => {
    const {record, language, setOfBooksId} = this.state;
    let param = {
      language,
      setOfBooksId,
      enableAutoUpdate: e.target.checked,
      currencyCode: record.currencyCode,
    };
    Modal.confirm({
      content: messages('setting.key416'/*是否确认修改*/),
      onOk: () => {
        CurrencySettingService.onAutoRateChange(param)
          .then(res => {
            this.getCurrencyDetail();
          });
      },
      onCancel: () => {
      },
    });
  };

  //点击更改
  onOperation = (event, record) => {
    this.setState({
      visible: true,
      originalRate: record.rate,
      operatedRecord: JSON.parse(JSON.stringify(record))
    })
  };

  //更改历史汇率
  onHistoryRateChange = (value) => {
    const {operatedRecord} = this.state;
    operatedRecord.rate = value;
    this.setState({
      operatedRecord,
    })
  };

  //更改历史汇率模态框的确定
  handleModalOK = () => {
    const {operatedRecord} = this.state;
    if (typeof (operatedRecord.rate) !== 'number' || operatedRecord.rate <= 0) {
      message.error(messages('setting.key403'/*生效汇率必须为大于0的数字*/) /*生效汇率必须为大于0的数字*/)
    } else {
      CurrencySettingService.handleModalOK(operatedRecord)
        .then(res => {
          message.success(messages('setting.key260'/*修改成功*/));
          this.getCurrencyDetail();
          this.setState({
            visible: false,
            historyRateSave: true,
          });
        })
        .catch(err => {
          message.error(messages('setting.key417'/*修改失败*/));
        })
    }
  };

  //更改历史汇率模态框的取消
  handleModalCancel = () => {
    this.setState({
      visible: false,
    })
  };

  //查询的初始日期
  startDateChange = (date) => {
    this.setState({
      startDate: date,
    });
  };

  //查询的结束日期
  endDateChange = (date) => {
    this.setState({
      endDate: date,
    });
  };

  //开始查询日期 <= 结束查询日期
  disabledStartDate = (startDate) => {
    let endDate = moment(moment(this.state.endDate).format('YYYY-MM-DD 23:59:59'));
    if (!startDate || !endDate) {
      return false;
    }
    return startDate.valueOf() > endDate.valueOf()
  };

  //结束查询日期 >= 开始查询日期 且 结束代理日期 <= 今天
  disabledEndDate = (endDate) => {
    const startDate = moment(moment(this.state.startDate).format('YYYY-MM-DD 00:00:00'));
    if (!endDate || !startDate) {
      return false;
    }
    if (startDate.valueOf() < new Date().valueOf()) {
      let end = this.getAfterDate(1, moment(new Date()).format('YYYY.MM.DD'));
      return endDate.valueOf() > moment(end).valueOf()
    }
    return endDate.valueOf() < startDate.valueOf()
  };

  getAfterDate = (afterDays, dateStr) => {
    let date = new Date(dateStr);// it's today
    let oneDayTime = afterDays * 24 * 60 * 60 * 1000;// ms
    let newDate = new Date(date.getTime() + oneDayTime);
    return moment(newDate).format('YYYY-MM-DD');
  };

  //清空查询条件
  clearSearch = () => {
    this.setState({
      page: 0,
      startDate: null,
      endDate: null,
    }, () => {
      this.getRateHistory();
    });
  };

  //不能选择今天之后
  disabledDate = (endValue) => {
    const startValue = new Date();
    if (!endValue || !startValue) {
      return false;
    }
    return endValue.valueOf() > startValue.valueOf();
  };

  goBack = () => {
    const {setOfBooksId} = this.state;
    this.context.router.push(this.currencySetting.url.replace(":setOfBooksId", setOfBooksId))
  };

  render () {
    const dateFormat = 'YYYY/MM/DD';
    const {record, isBaseCurrency, columns, data, pagination, visible, operatedRecord, outEditRate,
           startDate, endDate, originalRate, enableAutoUpdate, loading, saveLoading} = this.state;
    return (
      isBaseCurrency ?
        <div className='currency-edit-base'>
          <div className="title-container">
            {messages('setting.key418'/*编辑汇率*/)}
            <Divider/>
          </div>
          <div className='currency-edit-base-content'>
            <Row gutter={24}>
              <Col span={8}>
                {messages('setting.key399'/*币种名*/)}&nbsp;&nbsp;&nbsp;
                {record.baseCurrencyName}
              </Col>
              <Col span={8}>
                {messages('setting.key400'/*代码*/)}&nbsp;&nbsp;
                {record.baseCurrencyCode}
              </Col>
              <Col span={8}>
                {messages('setting.key1485')/*币种精度*/}&nbsp;&nbsp;
                {queryCurrencyPrecision(record.baseCurrencyCode)}
              </Col>
            </Row>
          </div>
          <div className="title-container">
            <Divider/>
            <a onClick={this.goBack}><Icon type="rollback" />{messages("common.back")/*返回*/}</a>
          </div>
        </div>
        :
        <div className='currency-edit-notBase'>
          <div className="title-container">
            {messages('setting.key418'/*编辑汇率*/)}
            <Divider/>
          </div>
          {record.enable ?
            messages('setting.key419'/*已启用*/)
            :
            messages("common.disabling")/*已禁用*/}&nbsp;&nbsp;&nbsp;
          <Switch checked={record.enable} onChange={this.onEnableRate} disabled={!this.props.tenantMode}/>
          <Divider/>
          <div className='currency-edit-notBase-content'>
            <Row gutter={24} style={{marginBottom: 20}}>
              <Col span={8}>
                {messages('setting.key399'/*币种名*/)}&nbsp;&nbsp;&nbsp;
                {record.currencyName}
              </Col>
              <Col span={8}>
                {messages('setting.key400'/*代码*/)}&nbsp;&nbsp;
                {record.currencyCode}
              </Col>
              <Col span={8}>
                {messages('setting.key404'/*启用自动汇率:*/)}&nbsp;&nbsp;&nbsp;
                {
                  <Checkbox checked={record.enableAutoUpdate}
                            onChange={this.onEnableAutoUpdate}
                            disabled={!this.hasAnyAuthorities(['ROLE_TENANT_ADMIN']) || !enableAutoUpdate || outEditRate || !this.props.tenantMode}/>
                }
              </Col>
            </Row>
            {outEditRate ?
              <Row gutter={24}>
                <Col span={8}>
                  {messages('setting.key401'/*汇率生效日期*/)}&nbsp;&nbsp;
                  <DatePicker defaultValue={moment(moment(new Date()).format("YYYY-MM-DD"))}
                              format={dateFormat}
                              onChange={this.outApplyDateChange}
                              disabledDate={this.disabledDate}
                              allowClear={false}/>
                </Col>
                <Col span={8}>{messages('setting.key402'/*生效汇率*/)}&nbsp;&nbsp;
                  <InputNumber value={record.rate}
                               onChange={this.outRateChange}
                               min={0.01}
                               precision={2}
                               step={0.01}/>
                </Col>
                <Col span={8}>
                  {messages('setting.key1485')/*币种精度*/}&nbsp;&nbsp;
                  {queryCurrencyPrecision(record.currencyCode)}
                </Col>
              </Row>
              :
              <Row gutter={24}>
                <Col span={8}>{messages('setting.key401'/*汇率生效日期*/)}&nbsp;&nbsp;
                  {moment(record.applyDate).local().format('YYYY-MM-DD')}
                </Col>
                <Col span={8}>{messages('setting.key402'/*生效汇率*/)}&nbsp;&nbsp;{record.rate}</Col>
                <Col span={8}>
                  {messages('setting.key1485')/*币种精度*/}&nbsp;&nbsp;
                  {queryCurrencyPrecision(record.currencyCode)}
                </Col>
              </Row>
            }
            <Divider/>
            {
              this.props.tenantMode && !outEditRate &&
              <Button type='primary'
                      disabled={record.enableAutoUpdate}
                      onClick={this.onOutEditRate}>
                {messages('setting.key420'/*更改汇率*/)}
              </Button>
            }
            {
              outEditRate &&
              <span>
                  <Button onClick={this.onOutEditRateCancel}>
                    {messages('setting.key421'/*取消修改*/)}
                  </Button>
                  <Button onClick={this.onOutEditRateSave}
                          style={{marginLeft: 20}}
                          type='primary'
                          loading={saveLoading}>
                    {messages("common.save")/*保存*/}
                  </Button>
                </span>
            }
            <div className='currency-edit-block' style={{marginTop: 20}}>
              <span className='currency-edit-history-left' style={{fontSize: 18}}>
                {messages('setting.key422'/*汇率历史*/)}
              </span>
              <div className='currency-edit-history-right' style={{float: 'right'}}>
                <span>
                {messages('setting.key401'/*汇率生效日期*/)}&nbsp;&nbsp;&nbsp;
              </span>
                <DatePicker format={dateFormat}
                            value={startDate}
                            placeholder={messages('setting.key423'/*开始日期*/)}
                            onChange={this.startDateChange}
                            disabledDate={this.disabledStartDate}
                            allowClear/>
                &nbsp;&nbsp;{messages('setting.key424'/*至*/)}&nbsp;&nbsp;
                <DatePicker format={dateFormat}
                            value={endDate}
                            placeholder={messages("common.end.date")/*结束日期*/}
                            onChange={this.endDateChange}
                            disabledDate={this.disabledEndDate}
                            allowClear/>
                <Button style={{marginRight: 20, marginLeft: 30}} onClick={this.clearSearch}>
                  {messages('setting.key425'/*重置查询条件*/)}
                </Button>
                <Button type='primary'
                        onClick={this.onSearch}>
                  {messages('setting.key426'/*查询*/)}
                </Button>
              </div>
            </div>
            <div className='currency-edit-table' style={{marginTop: 30}}>
              <ResizeTable columns={columns} dataSource={data} pagination={pagination} size={'middle'} loading={loading} bordered/>
            </div>
            <div>
              <Modal visible={visible}
                     onCancel={this.handleModalCancel}
                     footer={(
                       <div>
                         <Button style={{ marginRight: 8 }} onClick={this.handleModalCancel}>{messages('common.cancel')}</Button>
                         <Button type="primary" onClick={this.handleModalOK} disabled={operatedRecord.rate === originalRate}>{messages('common.ok')}</Button>
                       </div>
                     )}
                     title={messages('setting.key427'/*更改历史汇率*/)}>
                <div>
                  {messages('setting.key401'/*汇率生效日期*/)}
                  &nbsp;&nbsp;&nbsp;{moment(operatedRecord.applyDate).local().format('YYYY-MM-DD HH:mm:ss')}
                </div>
                <div>{messages("common.currency.rate")/*汇率*/}&nbsp;&nbsp;&nbsp;
                  <span>
                    <InputNumber min={0.01}
                                 precision={2}
                                 step={0.01}
                                 onChange={this.onHistoryRateChange}
                                 value={operatedRecord.rate}/>
                  </span>
                </div>
              </Modal>
            </div>
          </div>
          <div className="title-container">
            <Divider/>
            <a onClick={this.goBack}><Icon type="rollback" />{messages("common.back")/*返回*/}</a>
          </div>
        </div>
    )
  }
}

CurrencySettingEdit.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    company: state.login.company,
    tenantMode: state.main.tenantMode,
  }
}

export default connect(mapStateToProps)(CurrencySettingEdit)
